package com.ceadeal.admin.service.user;

import com.ceadeal.admin.common.datatable.DataTableOutput;
import com.ceadeal.admin.mapper.user.UserMapper;
import com.ceadeal.admin.service.BaseService;
import com.ceadeal.admin.util.EncryptUtil;
import com.ceadeal.admin.vo.param.SearchParams;
import com.ceadeal.admin.entity.User;
import com.ceadeal.admin.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 功能描述: 用户
 *
 * 作者: Yzw
 * 日期: 2017-03-08 09:42:47
 */
@Service
@Transactional
public class UserService extends BaseService<User> {

    private static Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    /**
     * 功能描述: 分页查询
     * @param
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2017-03-08 10:37:02
     */
    @Transactional(readOnly = true)
    public DataTableOutput findByPaging(SearchParams sp) {
        List<User> list = this.userMapper.findListByPaging(sp);
        int count = this.userMapper.getCountByPaging(sp);
        // 封装并返回
        return new DataTableOutput<>(sp.getDraw(), count, list);
    }

    /**
     * 功能描述：保存处理
     *
     * @param
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2017-03-08 21:40:42
     */
    public void saveHandler(User user) {
        Date currDate = new Date();
        String encodePassword = null;
        if (StringUtil.isNotEmpty(user.getPassword())) {
            encodePassword = EncryptUtil.encode(user.getPassword());
            user.setPassword(encodePassword);
        }
        if (user.getId() == null) {
            user.setCreateDate(currDate);
        }
        user.setPassword(encodePassword);
        user.setUpdateDate(currDate);
        this.saveOrUpdate(user);
    }

    public int saveOrUpdate(User user) {
        return user.getId() == null ? this.save(user) : this.update(user);
    }

    /**
     * 功能描述: 根据用户名获取用户
     * @param
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2017-03-24 13:16:03
     */
    @SuppressWarnings("Duplicates")
    @Transactional(readOnly = true)
    public User findByUserName(String userName) {
        User user = null;
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName", userName);
        List<User> list = this.userMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            user = list.get(0);
        }
        return user;
    }

}
